package com.hq.ims.data.aop;

import com.hq.ims.data.entity.LogSysException;
import com.hq.utils.util.StringUtils;
import com.hq.web.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 用户操作aop
 */
@Aspect
@Component
@Slf4j
public class SysExceptionLogAop {

    @Resource
    private ApplicationContext applicationContext;

    @Pointcut(value = "execution(* com.hq.ims..controller.*.*(..))")
    private void controllerAspect() {
    }

    @Around(value = "controllerAspect()")
    public Object recordLog(ProceedingJoinPoint point) throws Throwable {
        String uri = WebUtils.getUrl();
        //获取目标类
        Class clazz = point.getTarget().getClass();
        //获取目标方法名称
        String methodName = point.getSignature().getName();
        Object ret = null;
        try {
            ret = point.proceed();
        } catch (Throwable e) {
            LogSysException logSysAccess = new LogSysException();

            int firstIndex = e.toString().indexOf(":");
            String exceptionMainName = StringUtils.EMPTY;
            if (firstIndex > 0) {
                exceptionMainName = e.toString().substring(0, firstIndex);
            }
            logSysAccess.setExceptionMainName(exceptionMainName);
            logSysAccess.setExceptionDetail(this.getExceptionStr(e));
            logSysAccess.insert();
            throw e;
        }
        return ret;
    }

    private String getExceptionStr(Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }
}
